<?php
/*
* @Description: 这个是编写自定义接口的地方，用于前端AJAX请求
* @Autor: HuiSir<273250950@qq.com>
* @Date: 2024-05-28 10:27:13
 * @LastEditTime: 2024-08-21 22:58:31
*/

/* 评论相关 */

// 评论配置信息

function comment_config_callback( $request ) {
    // 文章id
    $id = $request[ 'id' ];
    // 用户是否已登录
    $is_user_logged_in = is_user_logged_in();
    // 判断是否需要密码才能查看评论
    $post_password_required = post_password_required( $id );
    // 判断当前文章是否允许评论
    $comments_open = comments_open( $id );
    // 评论数量
    $get_comments_number = ( int )get_comments_number( $id );
    // 判断是否需要登录才可发表评论
    $comment_registration = get_option( 'comment_registration' ) ? true : false;
    // 评论者必须填入名字和电子邮箱地址
    $require_name_email = get_option( 'require_name_email' ) ? true : false;
    // 是否启用评论嵌套
    $thread_comments = get_option( 'thread_comments' ) ? true : false;
    // 评论嵌套层数
    $thread_comments_depth = ( int )get_option( 'thread_comments_depth' );
    // 评论排序：每个页面顶部显示旧评论还是新评论（asc-旧评论，desc-新评论）
    $comment_order = get_option( 'comment_order' );
    // 是否分页显示评论
    $page_comments = get_option( 'page_comments' ) ? true : false;
    // 是否显示头像
    $show_avatars = get_option( 'show_avatars' ) ? true : false;
    // 登录用户邮箱
    $current_user_email = wp_get_current_user() -> user_email;
    // 登录用户昵称
    $current_username = wp_get_current_user() -> display_name;
    return [
        'is_user_logged_in' => $is_user_logged_in,
        'post_password_required' => $post_password_required,
        'comments_open' => $comments_open,
        'get_comments_number' => $get_comments_number,
        'comment_registration' => $comment_registration,
        'require_name_email' => $require_name_email,
        'thread_comments' => $thread_comments,
        'thread_comments_depth' => $thread_comments_depth,
        'comment_order' => $comment_order,
        'page_comments' => $page_comments,
        'show_avatars' => $show_avatars,
        'current_user_email' => $current_user_email,
        'current_username' => $current_username,
    ];
}

// 时间显示方式'xx以前'

function timeAgo( $ptime ) {
    $ptime = strtotime( $ptime );
    $etime = time() - $ptime;
    if ( $etime < 1 ) return '刚刚';
    $interval = array (
        12 * 30 * 24 * 60 * 60  =>  '年前('.date( 'Y-m-d', $ptime ).')',
        30 * 24 * 60 * 60       =>  '个月前('.date( 'm-d', $ptime ).')',
        7 * 24 * 60 * 60        =>  '周前('.date( 'm-d', $ptime ).')',
        24 * 60 * 60            =>  '天前',
        60 * 60                 =>  '小时前',
        60                      =>  '分钟前',
        1                       =>  '秒前'
    );
    foreach ( $interval as $secs => $str ) {
        $d = $etime / $secs;
        if ( $d >= 1 ) {
            $r = round( $d );
            return $r . $str;
        }
    }
    ;
}

// 评论字段处理

function commentHandle( $comment, $comment_author, $comments, $floor ) {
    // 头像
    $comment->avatar_src = '//dn-qiniu-avatar.qbox.me/avatar/' .md5( $comment->comment_author_email ). '?s=50';
    // 子评论
    $comment->child_list = get_child_comments( $comment->comment_ID, $comment->comment_author, $comments );
    // 父名称
    $comment->parent_author = $comment_author;
    // 楼层（只限主评论）
    $comment->floor = $floor ? ( $floor == 1 ? '沙发' : $floor == 2 ? '板凳' : $floor. '楼' ) : null;
    // 时间显示（xx以前）
    $comment->time_ago = timeAgo( $comment->comment_date_gmt );
}

// 递归查询子评论

function get_child_comments( $parent_id, $comment_author, $comments ) {
    $child_comments = array();
    foreach ( $comments as $comment ) {
        if ( $comment->comment_parent == $parent_id ) {
            commentHandle( $comment, $comment_author, $comments );
            array_push( $child_comments, $comment );
            // 添加元素
        }
    }
    return $child_comments;
}

// 评论列表

function comment_list_callback( $request ) {
    $params = $request -> get_params();
    $postId = $params[ 'postId' ];
    $pageNum = ( int )$params[ 'pageNum' ];

    // 评论数量
    $get_comments_number = ( int )get_comments_number( $postId );
    // 默认显示最前一页还是最后一页（oldest-最前一页，newest-最后一页）
    $default_comments_page = get_option( 'default_comments_page' );
    // 每页显示条数
    $per_page = ( int )get_option( 'comments_per_page' );

    $args = array(
        'post_id' => $postId,
        'status' => 'approve', // 只获取已批准的评论
        'type' => 'comment',
        'number' => $per_page,
        'offset' =>  ( $pageNum - 1 ) * $per_page, // 从第几条开始的评论
        'order' => $default_comments_page === 'oldest' ? 'ASC' : 'DESC',
        'parent' => 0
    );

    $comments = get_comments( $args );
    $all_comments = get_comments( array(
        'post_id' => $postId,
        'status' => 'approve', // 只获取已批准的评论
    ) );

    foreach ( $comments as $index => &$comment ) {
        $floor = $get_comments_number - $index;
        commentHandle( $comment, null, $all_comments, $floor );
    }
    unset( $comment );

    return [
        'list' => $comments,
        'total' => $get_comments_number,
        'totalPage' => ceil( $get_comments_number / $per_page ),
    ];
}

// 发表评论

function comment_create_callback( $request ) {
    $params = $request -> get_params();
    $comment_ID = $params[ 'comment_ID' ];
    $comment_post_ID = $params[ 'comment_post_ID' ] ? ( int ) $params[ 'comment_post_ID' ] : 0;
    $comment_author = $params[ 'comment_author' ]  ? trim( $params[ 'comment_author' ] ) : null;
    $comment_author_email = $params[ 'comment_author_email' ]  ? trim( $params[ 'comment_author_email' ] ) : null;
    $comment_author_url = $params[ 'comment_author_url' ]  ? trim( $params[ 'comment_author_url' ] ) : null;
    $comment_content = $params[ 'comment_content' ]  ? trim( $params[ 'comment_content' ] ) : null;
    $post = get_post( $comment_post_ID );

    // 验证
    if ( empty( $post->comment_status ) ) {
        $error = '评论状态无效';
    }

    $post_status = get_post_status( $post );
    $post_status_obj = get_post_status_object( $post_status );

    if ( !comments_open( $comment_post_ID ) ) {
        $error = '本页评论已关闭';
    } elseif ( 'trash' == $status ) {
        $error = '评论状态无效';
    } elseif ( !$post_status_obj->public && !$post_status_obj->private ) {
        $error = '评论状态无效';
    } elseif ( post_password_required( $comment_post_ID ) ) {
        $error = '本页受密码保护';
    }

    $user = wp_get_current_user();

    if ( !$user->ID && ( get_option( 'comment_registration' ) || 'private' == $post_status ) ) {
        $error = '对不起，你必须登录后才能发表评论.';
    }

    if ( get_option( 'require_name_email' ) && !$user->ID ) {
        if ( '' == $comment_author_email || '' == $comment_author ) {
            $error = '请填写昵称和邮箱';
        } elseif ( 6 > strlen( $comment_author_email ) || !is_email( $comment_author_email ) ) {
            $error = '请输入有效的email地址';
        }
    }

    if ( '' == $comment_content ) {
        $error = '请输入评论';
    }

    if ( $error ) {
        return compact( 'error' );
    }

    // 提交
    try {
        if ( $comment_ID ) {
            // 更新评论
            wp_update_comment( $params );
        } else {
            // 创建新评论( 直接插入数据库, 避免二次验证 ), wp_new_comment函数会进行二次验证
            $comment_ID = wp_insert_comment( $params );
        }

        $comment = get_comment( $comment_ID );
        $comment->avatar_src = '//dn-qiniu-avatar.qbox.me/avatar/' .md5( $comment->comment_author_email ). '?s=50';
    } catch ( Exception $e ) {
        $error = $e->getMessage();
        // 返回自定义的异常信息
    }

    return compact( 'error', 'comment' );
}

/* 社交 */

// 打赏信息

function support_info_callback( $request ) {
    // 文章id
    $id = $request[ 'id' ];

    // 打赏说明
    $support_desc = get_post_meta( $id, 'support_desc', true );

    $options = get_option('theme_options');

    // 微信支付二维码
    $weixin_qrcode = $options['weixin_qrcode'];
    // 支付宝二维码
    $alipay_qrcode = $options['alipay_qrcode'];
    
    return [
        'support_desc' => $support_desc ? $support_desc : '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作！',
        'alipay_qrcode' => $alipay_qrcode,
        'weixin_qrcode' => $weixin_qrcode,
    ];
}

// get信息

function social_info_callback( $request ) {
    // 文章id
    $id = $request[ 'id' ];

    // 点赞数
    $like_count = ( int )get_post_meta( $id, 'like_count', true );

    // 分享数
    $share_count = ( int )get_post_meta( $id, 'share_count', true );

    // 评论数量
    $get_comments_number = ( int )get_comments_number( $id );

    return [
        'like_count' => $like_count ? $like_count : 0,
        'share_count' => $share_count ? $share_count : 0,
        'comments_count' => $get_comments_number,
    ];
}

// 点赞\分享数更新

function social_update_callback( $request ) {
    $params = $request -> get_params();
    $id = $params[ 'postId' ];
    $update_meta_key = $params[ 'metaKey' ];
    $num = (int)$params[ 'num' ] ;

    if ( $update_meta_key != 'like_count' && $update_meta_key != 'share_count' ) {
        return false;
    }

    $specs_raters = ( int )get_post_meta( $id, $update_meta_key, true );
    if ( !$specs_raters || !is_numeric( $specs_raters ) ) {
        update_post_meta( $id, $update_meta_key, 1 );
    } else {
        update_post_meta( $id, $update_meta_key, ( $specs_raters + ($num ? $num : 1) ) );
    }

    return ( int )get_post_meta( $id, $update_meta_key, true );
}

/* 搜索 */

/* 接口路由 */

function rest_API() {
    // 评论配置信息
    register_rest_route( 'theme_doubt/comment', 'config/(?P<id>[\d]+)', [
        'methods' => 'GET',
        'callback' => 'comment_config_callback'
    ] );
    // 评论列表
    register_rest_route( 'theme_doubt/comment', 'list', [
        'methods' => 'GET',
        'callback' => 'comment_list_callback'
    ] );
    // 发布评论
    register_rest_route( 'theme_doubt/comment', 'create', [
        'methods' => 'POST',
        'callback' => 'comment_create_callback'
    ] );
    // 打赏信息
    register_rest_route( 'theme_doubt/support', '(?P<id>[\d]+)', [
        'methods' => 'GET',
        'callback' => 'support_info_callback'
    ] );
    // 社交信息
    register_rest_route( 'theme_doubt/social', '(?P<id>[\d]+)', [
        'methods' => 'GET',
        'callback' => 'social_info_callback'
    ] );
    // 点赞、分享数据更新
    register_rest_route( 'theme_doubt/social', 'update', [
        'methods' => 'POST',
        'callback' => 'social_update_callback'
    ] );
}

/* 注册所有接口 */
add_action( 'rest_api_init', 'rest_API' );
?>